package cn.dengta.webapp.trade.entity.meta;

import java.util.*;
import java.util.stream.Collectors;

import cn.dengta.context.model.WesKit;
import cn.dengta.webapp.trade.entity.meta.MetaConfig.MetaRuleConfig;
import cn.dengta.webapp.user.model.Gender;
import lombok.Getter;
import lombok.Setter;
import lombok.experimental.Accessors;
import me.codeplayer.util.Assert;
import me.codeplayer.util.CollectionUtil;

/**
 * 牵线的规则配置对象
 * 第一个牵线备份
 */
@Getter
@Setter
public class PullWiresRuleV1 implements MetaRuleConfig {

	/** 男用户牵线参数 */
	public MaleEntry male;
	/** 女用户牵线参数 */
	public FemaleEntry female;
	/** 是否开启牵线 */
	public Boolean enabled;

	/** 分包牵线开关 */
	//public List<WesKitEnable> kitEnable;
	@Override
	public void validate() {
		Assert.isTrue(male != null && female != null, "男/女用户牵线配置不能为空！");
		//Assert.notNull(kitEnable, "分包牵线开关不能为空！");
		//kitEnable.forEach(WesKitEnable::validate);
		Assert.notNull(enabled, "牵线开关不能为空！");
		male.validate();
		female.validate();
	}

	@Override
	public void init(MetaRuleConfig config) {
		PullWiresRuleV1 rule = (PullWiresRuleV1) config;
		this.male = rule.male;
		this.female = rule.female;
		this.enabled = rule.enabled;
		//this.kitEnable = rule.kitEnable;
	}

	public PullLevel getAmount(Gender gender, Integer level) {
		if (gender == Gender.MALE) {
			Map<Integer, PullLevel> map = this.male.levels.stream().collect(Collectors.toMap(PullLevel::getLevel, l -> l));
			if (level == null) {
				level = this.male.defaultLevel;
			}
			return map.get(level);
		}
		if (gender == Gender.FEMALE) {
			Map<Integer, PullLevel> map = this.female.levels.stream().collect(Collectors.toMap(PullLevel::getLevel, l -> l));
			if (level == null) {
				level = this.female.defaultLevel;
			}
			return map.get(level);
		}
		return null;
	}

	/**
	 * 男用户牵线规则实体
	 */
	@Setter
	@Getter
	public static class MaleEntry {

		/** 默认等级 */
		protected Integer defaultLevel;
		/** 等级值 */
		protected List<PullLevel> levels;

		public void validate() {
			Assert.isTrue(defaultLevel >= 1 && defaultLevel <= 4, "默认等级必须在[1,4]");
			Assert.isTrue(levels.size() == 4, "等级数据必须为4个");
		}

	}

	@Getter
	@Setter
	public static class FemaleEntry extends MaleEntry {

		/** 判断最近 N 条是否回复 */
		private Integer recently;
		/** 如果未回复暂停N分钟 */
		private Integer pauseDuration;
		/** 是否牵线离线男用户 */
		private boolean offLine = false;

	}

	@Getter
	@Setter
	public static class PullLevel {

		/** 对应等级 */
		private Integer level;
		/** 牵线值（女）/推荐值（男） */
		private Integer value;
		/** 间隔时长： 单位分钟 */
		private Integer duration;

	}

	@Getter
	@Setter
	@Accessors(chain = true)
	public static class WesKitEnable {

		/** 对应分包 */
		private WesKit wesKit;
		/** 是否启用 */
		private Boolean enable;

		public void validate() {
			Assert.notNull(wesKit, "分包不能为空");
			Assert.notNull(enable, "是否启用不能为空");
		}

		public Integer getWesKit() {
			return wesKit.getValue();
		}

		public String getWesKit_() {
			return wesKit.getLabel();
		}

	}

}
